package com.roadjava.rbac.security;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.filter.GenericFilterBean;

import java.io.IOException;

public class DecryptionFilter extends GenericFilterBean {

    private final String secretKey;

    public DecryptionFilter(String secretKey) {
        this.secretKey = secretKey;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        // 检查请求URI是否为/login
        if ("/user/login".equals(httpRequest.getRequestURI())) {
            String encryptedPassword = httpRequest.getParameter("pwd");
//            System.out.println("解密过滤器: 处理请求中");
//            System.out.println("解密过滤器: 密钥: " + secretKey);
//            System.out.println("未解密的密码: " + encryptedPassword);

            HttpServletRequest wrappedRequest = httpRequest;
            if (encryptedPassword != null) {
                try {
                    // 解密并设置为请求属性
                    String pwd = AESUtil.decrypt(encryptedPassword, secretKey);
                    wrappedRequest = new DecryptedHttpServletRequestWrapper(httpRequest, pwd);

                    // 打印解密后的密码
                    System.out.println("解密后的密码: " + pwd);
                } catch (Exception e) {
                    httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, "密码解密失败");
                    System.out.println("密码解密失败: " + e.getMessage());
                    return; // 阻止继续处理
                }
            }

            // 继续过滤，使用包装后的请求
            chain.doFilter(wrappedRequest, response);
        } else {
            // 如果不是/login接口，直接继续过滤
            chain.doFilter(request, response);
        }
    }
}
